import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/authentication.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/models/common/Passwords.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:reactive_forms/reactive_forms.dart';

class ResetStrongUserPasswordPage extends StatefulWidget {
  ResetStrongUserPasswordPage({
    Key? key,
    required this.isTeacherOrSchooladmin,
    required this.currentPassword,
    required this.remember,
  }) : super(key: key);
  final bool isTeacherOrSchooladmin;
  final String currentPassword;
  final bool remember;

  @override
  State<ResetStrongUserPasswordPage> createState() =>
      _ResetStrongUserPasswordPageState();
}

class _ResetStrongUserPasswordPageState
    extends State<ResetStrongUserPasswordPage> {
  final UserController _usercontroller = Get.find();
  final LoginController _loginController = Get.find();
  final box = Hive.box('appconfig');
  final String teacherPasswordMessage =
      '''*Passwords contain at least 12 characters, 1 number, 1 uppercase letter, and 1 special character.''';
  final String teacherPasswordMessage2 =
      '''*Passwords cannot be the same as the previous 5 account passwords.''';
  final String teacherPasswordMessage3 =
      '''*Passwords cannot contain any common dictionary words.''';

  @override
  Widget build(BuildContext context) {
    StrongPasswordFormTeacherModel formTeacherModel =
        StrongPasswordFormTeacherModel();
    var formTeacher = formTeacherModel.form;
    formTeacher.control('currentpassword').value = widget.currentPassword;
    bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;

    return Scaffold(
      resizeToAvoidBottomInset: true,
      body: Padding(
        padding: const EdgeInsets.all(18.0),
        child: Center(
          child: Column(
            mainAxisAlignment: GetPlatform.isWeb
                ? MainAxisAlignment.center
                : MainAxisAlignment.start,
            children: [
              Visibility(
                  visible: !GetPlatform.isWeb,
                  child: SizedBox(
                    height: 48,
                  )),
              Text(
                'For security reason, please change your password!'.tr,
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    letterSpacing: 1,
                    color: Get.isDarkMode ? Color(0xffcccccc) : Colors.black,
                    fontSize: 20),
              ),
              SizedBox(
                height: 24,
              ),
              Container(
                width: 600,
                height: 380,
                child: ReactiveForm(
                  formGroup: formTeacher,
                  child: Column(children: [
                    Expanded(
                        child: ReactiveTextField(
                      formControlName: 'currentpassword',
                      obscureText: true,
                      decoration: InputDecoration(
                        labelText: 'Current Password'.tr,
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8.0)),
                      ),
                    )),
                    Expanded(
                        child: ReactiveTextField(
                      formControlName: 'newpassword',
                      obscureText: true,
                      decoration: InputDecoration(
                        labelText: 'New Password'.tr,
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8.0)),
                        //hintText: 'Confirm Password'.tr
                      ),
                      validationMessages: {
                        ValidationMessage.pattern: (_) =>
                            'Password pattern not right'.tr
                      },
                    )),
                    Expanded(
                        child: ReactiveTextField(
                      formControlName: 'confirmpassword',
                      obscureText: true,
                      decoration: InputDecoration(
                        labelText: 'Confirm Password'.tr,
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8.0)),
                        //hintText: 'Confirm Password'.tr
                      ),
                      validationMessages: {
                        ValidationMessage.mustMatch: (_) =>
                            'Confirm password doesn\'t match'.tr
                      },
                    )),
                    SizedBox(
                      height: 12,
                    ),
                    Visibility(
                        visible: widget.isTeacherOrSchooladmin,
                        child: Text(
                            '${teacherPasswordMessage.tr} \n${teacherPasswordMessage2.tr} \n${teacherPasswordMessage3.tr}')),
                    SizedBox(
                      height: 12,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        SizedBox(
                          width: 50,
                        ),
                        MaterialButton(
                            color: Get.isDarkMode
                                ? (Colors.white)
                                : Theme.of(context).primaryColorDark,
                            textColor: Get.isDarkMode
                                ? (Colors.black)
                                : Theme.of(context).primaryColorLight,
                            onPressed: () {
                              Get.offAndToNamed('/login');
                            },
                            child: Text('Cancel'.tr)),
                        SizedBox(
                          width: 20,
                        ),
                        ReactiveFormConsumer(
                          builder: (context, form, child) {
                            return MaterialButton(
                                color: Get.isDarkMode
                                    ? (Colors.white)
                                    : Theme.of(context).primaryColorDark,
                                textColor: Get.isDarkMode
                                    ? (Colors.black)
                                    : Theme.of(context).primaryColorLight,
                                onPressed: () {
                                  if (form.valid) {
                                    Passwords passwords = new Passwords(
                                        newPassword:
                                            form.control('newpassword').value,
                                        password: form
                                            .control('currentpassword')
                                            .value);

                                    _usercontroller
                                        .resetStrongUserPassword(passwords)
                                        .then((statusMessage) {
                                      if (statusMessage.status == 1000) {
                                        showSnackMsg(
                                            'Password reset successfully!');
                                        Future.delayed(
                                            Duration(milliseconds: 1000), (() {
                                          if (widget.remember) {
                                            _loginController.savePassword(
                                                passwords.newPassword);
                                          } else {
                                            _loginController.removePassword();
                                          }
                                          if (isTeacher) {
                                            Get.offAndToNamed('/teacher/home');
                                          } else {
                                            Get.offAllNamed(
                                                '/schooladmin/home');
                                          }
                                        }));
                                      } else {
                                        showSnackMsg(statusMessage.message!);
                                      }
                                    });
                                  } else {
                                    form.markAllAsTouched();
                                  }
                                },
                                child: Text('Submit'.tr));
                          },
                        ),
                      ],
                    ),
                  ]),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
